<template>
  <div class="subscribeManager">
    <x-header class="header" :left-options="{showBack: showHeaderBack,preventGoBack:true}" @on-click-back="goToPage('/')" ref="header">
      客户预订管理<a slot="right" @click="showBtnMenus = true" >新建预订</a>
    </x-header>
    <div class="topHolder"></div>
    <box gap="1rem 0.8rem">
      <group-title ref="subscribeTotals" class="subscribeTotals">
        今天预订数量：
        <span v-for="(item,index) in subscribeTotals" :key="index">
          <span v-text="item.name"></span>（<span v-text="item.total"></span>）
        </span>
      </group-title>
      <div class="filterArea" ref="filterArea">
        <div class="filterItem"><x-button @click.native="showUsersByDepart = true" type="default" v-html="usersByDepartText" :show-loading="loadingStatus" :disabled="loadingStatus" class="inlineBtn popPickerBtn"></x-button></div>
        <div class="filterItem"><x-button @click.native="showSubscribeStatus = true" type="default" v-html="$refs.subscribeStatus&&$refs.subscribeStatus.getNameValues()+'<i class=\'iconfont icon-xiangxia2\'></i>'" :show-loading="loadingStatus" :disabled="loadingStatus" class="inlineBtn popPickerBtn"></x-button></div>
      </div>
      <popup-picker @on-change="changeUsersByDepartText();refreshList()" :show.sync="showUsersByDepart" :show-cell="false" :data="usersByDepart" :columns="2" v-model="choosenDepartAndUser" ref="usersByDepart" class="btn_popup-picker"></popup-picker>
      <popup-picker @on-change="refreshList()" :show.sync="showSubscribeStatus" :show-cell="false" :data="subscribeStatus" :columns="1" v-model="choosenSubscribeStatus" ref="subscribeStatus" class="btn_popup-picker"></popup-picker>
      <scroller :height="scrollerHeight" lock-x use-pulldown use-pullup :pulldown-config="pulldownDefaultConfig" @on-pulldown-loading="refreshList()" :pullup-config="pullupDefaultConfig" @on-pullup-loading="loadMoreList" ref="loadMoreScroller" >
        <div class="subscribeList">
          <div class="item" v-for="(item,index) in subscribeList" :key="index" @click="doAction(item)">
            <h5 class="name">客户：<span v-html="item.CUSTOMER_NAME"></span></h5>
            <div class="state">
              <span v-if="item.STATE == 0" class="waiting">预订待分配</span>
              <span v-if="item.STATE == 1" class="success">分配成功</span>
              <span v-if="item.STATE == 2" class="error">分配失败</span>
              <span v-if="item.STATE == 3" class="cancel">已取消</span>
              <span v-if="item.STATE == 4" class="arrived">已到店</span>
              <span v-if="item.STATE == 5" class="timeout">超时未到店</span>
              <span v-if="item.STATE == 6" class="opened">已开单</span>
              <span v-if="item.STATE == 7" class="saled">已点单</span>
              <span v-if="item.STATE == 9" class="clear">已结账</span>
              <span v-if="item.STATE == 8" class="unpay">未支付押金</span>
            </div>
            <span class="saled">已消费：¥ <span v-html="formatCurrency(item.saled)"></span>元</span>
            <span class="presented">已赠送：¥ <span v-html="formatCurrency(item.presented)"></span>元</span>
            <span class="subscriber">预订人：<span v-html="item.subscribe_DEPARTMENT"></span> - <span v-html="item.SUBSCRIBER"></span></span>
            <span class="dateTime">预订时间：<span v-html="item.SUBSCRIBE_DATETIME"></span></span>
            <span class="table">已分配房台：
              <span v-if="item.AREA && item.NUMBER && item.ROOM_PLATFORM_TYPE && item.AREA != '' && item.NUMBER != '' && item.ROOM_PLATFORM_TYPE != ''">
                <span v-html="item.AREA"></span> - <span v-html="item.NUMBER"></span>（<span v-html="item.ROOM_PLATFORM_TYPE"></span>）
              </span>
              <span v-else>-</span>
            </span>
          </div>
          <div class="listNoItem" v-if="subscribeList.length <= 0">暂无预订</div>
        </div>
      </scroller>
      <actionsheet v-model="showBtnMenus" :menus="btnMenus" @on-click-menu="btnMenusClick" show-cancel></actionsheet>
      <actionsheet v-model="showActionsheet" :menus="actionsheetMenu" @on-click-menu="actionsheetClick" show-cancel></actionsheet>
      <actionsheet v-model="showActionsheet2" :menus="actionsheetMenu2" @on-click-menu="actionsheetClick2" show-cancel></actionsheet>
    </box>
  </div>
</template>

<script>
  import { XButton, Box, Group, GroupTitle, PopupPicker, Scroller, Actionsheet, numberComma } from 'vux'
  import {getSubscribeTotals,getUsersByDepart,getSubscribeIdList,getSubscribeByIds} from "../../api";
  import {message,toDecimal2} from "../../common/util";

  export default {
    name:'subscribeManager',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        loadingStatus:false,
        subscribeTotals:[],
        usersByDepartText:'',
        showUsersByDepart: false,
        choosenDepartAndUser:['allDepart','allPerson'],
        showSubscribeStatus: false,
        subscribeStatus:[
          {name: '所有预订状态',value: 'all'},
          {name: '预约待分配',value: '0'},
          {name: '未支付押金',value: '8'},
          {name: '分配成功',value: '1'},
          {name: '分配失败',value: '2'},
          {name: '已取消',value: '3'},
          {name: '已到店',value: '4'},
          {name: '超时未到店',value: '5'},
          {name: '已开单',value: '6'},
          {name: '已点单',value: '7'},
          {name: '已结账',value: '9'}
        ],
        choosenSubscribeStatus:['all'],
        subscribeList:[],
        idArrayList:[],
        scrollerHeight:'',
        pulldownDefaultConfig:{
          content: '下拉刷新',
          height: 40,
          autoRefresh: false,
          downContent: '下拉刷新',
          upContent: '释放后刷新',
          loadingContent: '正在刷新...',
          clsPrefix: 'xs-plugin-pulldown-'
        },
        pullupDefaultConfig:{
          content: '上拉加载更多',
          pullUpHeight: 60,
          height: 40,
          autoRefresh: false,
          downContent: '释放后加载',
          upContent: '上拉加载更多',
          loadingContent: '加载中...',
          clsPrefix: 'xs-plugin-pullup-'
        },
        currentPage: 0,
        totalItems:0,
        pageSize:8,
        onFetching:true,
        showBtnMenus:false,
        btnMenus:[
          {label: '新建预订',type: 'Default',value: 'addSubBtn'},
          {label: '节日/派对预订',type: 'Default',value: 'partySubBtn'}
        ],
        showActionsheet:false,
        actionsheetMenu:[
          {label: '预订详情',type: 'Default',value: 'subscribeDetail'},
          {label: '订单详情',type: 'Default',value: 'orderDetail'}
          /*,{label: '赠送酒水',type: 'Default',value: 'present'},
          {label: '替客户存酒',type: 'Default',value: 'keepWine'},
          {label: '查看客户详情',type: 'Default',value: 'customerDetail'}*/
        ],
        showActionsheet2:false,
        actionsheetMenu2:[
          {label: '普通签送（售卖库存）',type: 'Default',value: 'salePresent'},
          {label: '普通签送（存酒库存）',type: 'Default',value: 'keepPresent'}
          /*,{label: '过期酒水签送',type: 'Default',value: 'expiredWinePresent'}*/
        ],
        clickedItem:{}
      }
    },
    components: {
      XButton,
      Box,
      Group,
      GroupTitle,
      PopupPicker,
      Scroller,
      Actionsheet
    },
    computed:{
      usersByDepart:{
        get(){
          return this.$store.getters.getUsersByDepart_all
        },
        set(value){
          this.$store.commit('updateUsersByDepart_all', value)
        }
      }
    },
    methods:{
      goToPage(){
        this.$router.push({path:'/'})
      },
      formatCurrency(number){
        return numberComma(toDecimal2(number))
      },
      refreshList(params){
        this.loadingStatus = true
        this.subscribeList = []
        this.currentPage = 0
        let reqParams = {
          choosenSubscribeStatus:this.choosenSubscribeStatus,
          choosenDepartAndUser:this.choosenDepartAndUser
        }
        getSubscribeIdList(reqParams).then((res)=>{
          if(res.status == 'success'){
            this.$nextTick(() => {
              if(this.$refs.loadMoreScroller){
                this.$refs.loadMoreScroller.reset({top: 0})
                this.$refs.loadMoreScroller.donePulldown()
              }
              this.idArrayList = res.data
              this.totalItems = res.data.length
              this.loadMoreList({callback:(params && params.callback)?params.callback:null})
            })
          }else if(res.status == 'error') {
            message({message:res.msg,type:'error'})
            console.log('getSubscribeIdList error info:', res.msg)
          }
        }).catch((err)=>{console.log('getSubscribeIdList catch info:',err)})
      },
      loadMoreList(params){
        if (this.onFetching) {
          this.onFetching = false
          setTimeout(() => {
            let reqParams = [],start = this.currentPage*this.pageSize,end = start + this.pageSize - 1
            for(var i = start; i <= end; i++){
              if(this.idArrayList[i] != undefined)reqParams.push(this.idArrayList[i])
            }
            getSubscribeByIds(reqParams).then((res)=>{
              if(res.status == 'success'){
                if(res.data.length > 0){//后端实际用这个
                  //if (this.subscribeList.length < this.totalItems) {//前端测试用这个
                  for(var i = 0; i < res.data.length; i++){
                    this.subscribeList.push(res.data[i])
                  }
                  this.currentPage++
                }else{
                  message({message:'已经加载到底了！',type:'info'})
                }
                this.onFetching = true
                this.$nextTick(() => {
                  if(this.$refs.loadMoreScroller != undefined){
                    this.$refs.loadMoreScroller.donePullup()
                    this.$refs.loadMoreScroller.reset()
                  }
                })
              }else if(res.status == 'error') {
                message({message:res.msg,type:'error'})
                console.log('getSubscribeByIds error info:', res.msg)
              }
              this.setSize()
              this.loadingStatus = false
              if(params && params.callback && typeof params.callback == 'function')params.callback()
            }).catch((err)=>{console.log('getSubscribeByIds catch info:',err)})
          }, 1)
        }
      },
      setSize(){
        let outHeight = 0
        if(this.$refs.header)
        outHeight = this.$refs.header.$el.offsetHeight + this.$refs.subscribeTotals.$el.offsetHeight + this.$refs.filterArea.offsetHeight
        let contentHeight = window.screen.height - outHeight - 150
        this.scrollerHeight = contentHeight + 'px'
      },
      doAction(item){
        this.clickedItem = item
        switch (item.STATE) {
          case 0:
          case 1:
          case 2:
          case 3:
          case 5:
          case 4:
          case 8:this.$router.push({name:'预订详情',params:{subscribeId:item.SUBSCRIBE_ID,type:'edit'}});break
          case 6:
          case 7:
          case 9:this.showActionsheet = true;break
          default:break
        }
      },
      btnMenusClick(key, item) {
        if(key == 'addSubBtn'){
          this.$router.push({name:'增加预订',params:{subscribe:'normal'}})
        }else if(key == 'partySubBtn'){
          this.$router.push({path:'/holidayPartyList'})
        }
      },
      actionsheetClick (key, item) {
        //console.log(key, item)
        if(key == 'present'){
          switch (this.clickedItem.STATE) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 5:
            case 4:
            case 8:message({message:'该预订未开单成功，无法赠送',type:'error'});break
            case 6:
            case 9:this.showActionsheet2 = true;break
            case 7:
              //message({message:'未消费的订单无法赠送',type:'error'})
              this.showActionsheet2 = true;break
            default:break
          }
        }else if(key == 'orderDetail'){
          this.$router.push({name:'订单详情',params:{orderId:this.clickedItem.ORDER_ID}})
        }else if(key == 'subscribeDetail'){
          this.$router.push({name:'预订详情',params:{subscribeId:this.clickedItem.SUBSCRIBE_ID,type:'edit'}})
        }
      },
      actionsheetClick2 (key, item) {
        //console.log(key, item)
        if(key == 'salePresent'){
          this.$router.push({name:'选择要赠送商品',params:{type:'salePresent',orderId:this.clickedItem.ORDER_ID}})
        }else if(key == 'keepPresent'){
          this.$router.push({name:'选择要赠送商品',params:{type:'keepPresent',orderId:this.clickedItem.ORDER_ID}})
        }else if(key == 'expiredWinePresent'){

        }
      },
      changeUsersByDepartText(){
        this.usersByDepartText = this.$refs.usersByDepart&&this.$refs.usersByDepart.getNameValues().replace(/ /g,' / ')+'<i class=\'iconfont icon-xiangxia2\'></i>'
      }
    },
    mounted(){
      let funcArray = [getSubscribeTotals()]
      if(this.usersByDepart.length <= 0) funcArray.push(getUsersByDepart())
      Promise.all(funcArray).then((res)=> {
        for(let dataObj of res){
          if(dataObj.status == 'success'){
              if(dataObj.data.length > 0 && dataObj.data[0].value) this.usersByDepart = dataObj.data
              else if(dataObj.data.length > 0 && dataObj.data[0].total >= 0) this.subscribeTotals = dataObj.data
          }else if(dataObj.status == 'error') {
            message({message:dataObj.msg,type:'error'})
            console.log('getUsersByDepart & getSubscribeTotals error info:', dataObj.msg)
          }
        }
      }).then(()=>{
        this.choosenDepartAndUser = ['allDepart','allPerson']
        setTimeout(()=>{this.changeUsersByDepartText()},200)
        this.refreshList({callback: ()=>{
            window.onresize = ()=>{
              this.setSize()
            }
          }})
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      })
    },
    beforeDestroy(){
      window.onresize = ()=>{}
    }
  }
</script>

<style lang="scss" scoped>
  .subscribeManager{
    .subscribeTotals{margin: 0 0 0.5rem;padding: 0;}
    .filterArea{
      .filterItem{margin-bottom: 0.5rem;}
    }
    .subscribeList{
      display: flex;flex-wrap:wrap;justify-content:space-between;
      .item{
        position: relative;overflow:hidden;min-height:5rem;width: 44%;margin:0 0 1rem;padding:0.8rem 2%;border-radius: 0.3rem;font-size:0.7rem;
        background-color: #e9e9e9;
        background-image: -webkit-linear-gradient(top,#ffffff,#e9e9e9);
        background-image: -moz-linear-gradient(top,#ffffff,#e9e9e9);
        background-image: -ms-linear-gradient(top,#ffffff,#e9e9e9);
        background-image: -o-linear-gradient(top,#ffffff,#e9e9e9);
        background-image: linear-gradient(top,#ffffff,#e9e9e9);
        -webkit-box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.2);
        box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.2);
        .name{font-size:0.8rem;margin:1rem 0 0.3rem;overflow: hidden;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;}
        .state{position:absolute;right:0.4rem;top:0.6rem;
          span{
            color: #fff;padding:0.15rem 0.4rem;border-radius: 0.3rem;
            &.waiting{background: #ffaf29;}
            &.success{background: #00bdb9;}
            &.error{background: #bd2a78;}
            &.cancel{background: #bd2c00;}
            &.arrived{background: #1366bd;}
            &.timeout{background: #bdb908;}
            &.opened{background: #bd5909;}
            &.saled{background: #6fbd5b;}
            &.clear{background: #0abd39;}
            &.unpay{background: #a4a49e;}
          }
        }
        .saled{margin-bottom:0.3rem;overflow: hidden;display: -webkit-box;-webkit-line-clamp: 1;-webkit-box-orient: vertical;}
        .presented{margin-bottom:0.3rem;overflow: hidden;display: -webkit-box;-webkit-line-clamp: 1;-webkit-box-orient: vertical;}
        .subscriber{margin-bottom:0.3rem;overflow: hidden;display: -webkit-box;/*-webkit-line-clamp: 1;*/-webkit-box-orient: vertical;}
        .dateTime{margin-bottom:0.3rem;overflow: hidden;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;}
        .table{overflow: hidden;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;}
      }
    }
  }
</style>
